<?php
class FilesModel extends BaseModel implements Model {
    function __construct() {
        parent::__construct("files", "file_id");
        $this->addField("file_id", Model::TYPE_INT, Model::MOD_PRIMARY);
        $this->addField("filename", Model::TYPE_VARCHAR);
        $this->addField("owner", Model::TYPE_INT);
        $this->addField("content", Model::TYPE_VARCHAR);
        $this->addField("filetype", Model::TYPE_VARCHAR);
        $this->addField("thumbnail_content", Model::TYPE_VARCHAR);
    }

    public function renderAlias($record) {
        $result = $record;
        return $result;
    }

    public function retrieveImageById($id, $thumbnail) {
        $fileinfo = array();
        if ($id != "") {
            $fileinfo = $this->load($id);
        }
        if ($id == "") {
            headeR("Content-type: image/jpg");
            $size = filesize("site/resources/img/other/noimage.jpg");
            headeR("Content-length: $size");
            $fh = fopen("site/resources/img/other/noimage.jpg", "rb");
            fpassthru($fh);
            fclose($fh);
        } else if ($fileinfo['content'] != "") {   // megprobaljuk BLOB-bol kiolvasni
            header("Content-type: " . $fileinfo['filetype']);
            if ($thumbnail == "1" && $fileinfo['thumbnail_content'] != "") {
                echo $fileinfo['thumbnail_content'];
            } else {
                echo $fileinfo['content'];
            }
        } else if (file_exists("site/resources/img/" . $fileinfo['filename'])) {    // megprobaljuk fajlbol kiolvasni
            header("Content-type: " .$fileinfo['filetype']);
            $size = filesize("site/resources/img/" . $fileinfo['filename']);
            headeR("Content-length: $size");
            $fh = fopen("site/resources/img/" . $fileinfo['filename'], "r");
            fpassthru($fh);
            fclose($fh);
        } else {    // default kep
            headeR("Content-type: image/jpg");
            $size = filesize("site/resources/img/other/noimage.jpg");
            headeR("Content-length: $size");
            $fh = fopen("site/resources/img/other/noimage.jpg", "rb");
            fpassthru($fh);
            fclose($fh);
        }
        die();
    }

    public function isAuthorized($operation, $subject = "") {
        return true;
//        if (Auth::isAdmin()) { return true; }
/*
        switch ($operation) {
            case "update" :
            case "delete" :
            case "addnew" : {
                if (Auth::canChangeDrivers()) { return true; }
            }
            case "list" : {
                if (Auth::canListDrivers()) { return true; }
            }
        }
        return false;
*/
    }

    public function modifyDatabaseInput($data) {
        return $data;
    }
}

?>
